import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Spin, Form, Card, Row, Col, Table, Modal} from 'antd';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {getDetail, abandonData, publishData} from './api';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {DATE_FORMAT, DATETIME_FORMAT, TABLE} from '../constants';
import {serviceType, chargeMode, serviceActivityScope,
    conditionName, dataType, operator} from '../Enum';
import {formatDateTime, conventEnumValueToString, formatAmount} from '../utils';
import styles from './style.css';

const {Column} = Table;
const {Description} = DescriptionList;

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        detail: {},
        showMulValuePanel: false,
        currentConditionValues: [],
        currentConditionName: null
    };

    componentDidMount() {
        this.setState({loading: true});
        getDetail(this.props.id).then(res => {
            this.setState({
                loading: false,
                detail: res.data || {}
            });
        });
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        abandonData(this.props.id, {rowVersion: this.state.detail.rowVersion || ''}).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onSuccessReturn();
        });
    };

    handlePublishClick = () => {
        this.setState({
            loading: true
        });
        publishData(this.props.id, {rowVersion: this.state.detail.rowVersion || ''}).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onSuccessReturn();
        });
    };

    handleEdit=() => {
        this.props.history.push(routes.update.format(this.props.id));
    }

    onShowMulValuePanel=e => {
        const condition = this.state.detail.conditions.filter(v => v.id === e.target.dataset.id)[0];
        this.setState({
            showMulValuePanel: true,
            currentConditionName: condition.conditionName,
            currentConditionValues: condition.conditionValues
        });
    }
    onCloseMulValuePanel=() => {
        this.setState({
            showMulValuePanel: false,
            currentConditionValues: [],
            currentConditionName: null
        });
    }
    
    render() {
        const materialColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.usedPartCode',
                    defaultMessage: '旧件编号'
                }),
                dataIndex: 'usedPartCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.usedPartName',
                    defaultMessage: '旧件名称'
                }),
                dataIndex: 'usedPartName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.newPartCode',
                    defaultMessage: '新件编号'
                }),
                dataIndex: 'newPartCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.newPartName',
                    defaultMessage: '新件名称'
                }),
                dataIndex: 'newPartName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.materialprice',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.quantisCausedity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.isCaused',
                    defaultMessage: '是否主损件'
                }),
                dataIndex: 'isCaused',
                render: text => text ? this.props.intl.formatMessage({
                    id: 'detail.colums.y',
                    defaultMessage: '是'
                }) : this.props.intl.formatMessage({
                    id: 'detail.colums.n',
                    defaultMessage: '否'
                }),
            },
        ];
        const workItemColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.workItemCode',
                    defaultMessage: '维修项目编号'
                }),
                dataIndex: 'workItemCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.workItemName',
                    defaultMessage: '维修项目名称'
                }),
                dataIndex: 'workItemName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.laborHour',
                    defaultMessage: '工时'
                }),
                dataIndex: 'laborHour',
            },
        ];
        const conditionColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.conditionName',
                    defaultMessage: '条件名称'
                }),
                dataIndex: 'conditionName',
                render: text => conventEnumValueToString(conditionName, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.dataType',
                    defaultMessage: '数据类型'
                }),
                dataIndex: 'dataType',
                render: text => conventEnumValueToString(dataType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.operator',
                    defaultMessage: '运算符'
                }),
                dataIndex: 'operator',
                render: text => conventEnumValueToString(operator, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.value',
                    defaultMessage: '值'
                }),
                dataIndex: 'value',
                render: (text, r) => {
                    if(r.conditionName === conditionName.产品分类 || r.conditionName === conditionName.产品编号)
                        return <Button size="small" data-id={r.id} onClick={this.onShowMulValuePanel}>...</Button>;
                    return formatDateTime(text, DATE_FORMAT);
                }
            }
        ];

        const {options = []} = this.state.detail;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.publish) && hasPermissions(options, PERMISSION.publish))
            operations.push(
                <WrappedPopconfirm
                    id="publish"
                    key="publish"
                    title={this.props.intl.formatMessage({
                        id: 'detail.publish.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.publish.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.publish.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handlePublishClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.publish.popconfirm',
                            defaultMessage: '发布'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );

        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(
                <Button key="update" onClick={this.handleEdit} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.update',
                        defaultMessage: '编辑'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={this.props.intl.formatMessage({
                        id: 'detail.abandon.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.abandon.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.abandon.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.abandon.btn',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        
        return (
            <Form className="form-standard">
                <Spin spinning={this.state.loading}>
                   
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={6}>{this.props.intl.formatMessage({
                            id: 'detail.info.title',
                            defaultMessage: '基本信息'
                        })}</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col></Row>}>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.code',
                                    defaultMessage: '编号'
                                })}>
                                {this.state.detail.code}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.serviceName',
                                    defaultMessage: '名称'
                                })}>
                                {this.state.detail.serviceName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.serviceType',
                                    defaultMessage: '类型'
                                })}>
                                {conventEnumValueToString(serviceType, this.state.detail.serviceType) }
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.brandName',
                                    defaultMessage: '品牌'
                                })}>
                                {this.state.detail.brandName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.dealerName',
                                    defaultMessage: '总代'
                                })}>
                                {this.state.detail.dealerName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.content',
                                    defaultMessage: '活动内容'
                                })}>
                                {this.state.detail.content}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.chargeMode',
                                    defaultMessage: '计费模式'
                                })}>
                                {conventEnumValueToString(chargeMode, this.state.detail.chargeMode)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.frequency',
                                    defaultMessage: '单车可参加次数'
                                })}>
                                {this.state.detail.frequency}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.isRestrictedQuantity',
                                    defaultMessage: '是否限制台次'
                                })}>
                                { this.state.detail.isRestrictedQuantity
                                    ? this.props.intl.formatMessage({
                                        id: 'detail.yes',
                                        defaultMessage: '是'
                                    }) : this.props.intl.formatMessage({
                                        id: 'detail.no',
                                        defaultMessage: '否'
                                    })}
                            </Description>

                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.serviceQuantity',
                                    defaultMessage: '可参加总台次'
                                })}>
                                { this.state.detail.serviceQuantity}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.laborFee',
                                    defaultMessage: '工时费'
                                })}>
                                {formatAmount(this.state.detail.laborFee)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.materialFee',
                                    defaultMessage: '材料费'
                                })}>
                                {formatAmount(this.state.detail.materialFee) }
                            </Description>
                     
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.otherFee',
                                    defaultMessage: '其他费用'
                                })}>
                                {formatAmount(this.state.detail.otherFee)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.needMgmtFee*	',
                                    defaultMessage: '计算备件管理费'
                                })}>
                                {this.state.detail.needMgmtFee
                                    ? this.props.intl.formatMessage({
                                        id: 'detail.yes',
                                        defaultMessage: '是'
                                    }) : this.props.intl.formatMessage({
                                        id: 'detail.no',
                                        defaultMessage: '否'
                                    })}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.scope',
                                    defaultMessage: '服务活动适用范围'
                                })}>
                                {conventEnumValueToString(serviceActivityScope, this.state.detail.scope)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.startTime',
                                    defaultMessage: '开始时间'
                                })}>
                                {formatDateTime(this.state.detail.startTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.endTime',
                                    defaultMessage: '结束时间'
                                })}>
                                {formatDateTime(this.state.detail.endTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.remark',
                                    defaultMessage: '备注'
                                })}>
                                {this.state.detail.remark}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detail.materials.title',
                            defaultMessage: '维修材料清单属性列表'
                        })}>
                        <Table className="white-space-nowrap"
                            rowKey="id"
                            columns={materialColumns}
                            pagination={true}
                            dataSource={this.state.detail.materials}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detail.workItems.title',
                            defaultMessage: '维修项目清单属性列表'
                        })}>
                        <Table className="white-space-nowrap"
                            rowKey="id"
                            columns={workItemColumns}
                            pagination={true}
                            dataSource={this.state.detail.workItems}
                            {...TABLE} />
                    </Card>
                    {this.state.detail.vehicles && this.state.detail.vehicles.length > 0
                        ? <Card
                            title={this.props.intl.formatMessage({
                                id: 'detail.vehicleInfo.title',
                                defaultMessage: '指定车辆清单属性列表'
                            })}>
                            <Table className="white-space-nowrap"
                                rowKey="id"
                                pagination={true}
                                dataSource={this.state.detail.vehicles}
                                {...TABLE} >
                                <Column title={this.props.intl.formatMessage({
                                    id: 'detail.vehicleInfo.column.vin',
                                    defaultMessage: 'vin'
                                })} dataIndex="vin" ></Column>
                                <Column title={this.props.intl.formatMessage({
                                    id: 'detail.vehicleInfo.column.dutyDealerCode',
                                    defaultMessage: '责任服务站编号'
                                })} dataIndex="dutyDealerCode" ></Column>
                            </Table>
                        </Card>
                        : null
                    }
         
                    {this.state.detail.conditions && this.state.detail.conditions.length > 0
                        ? <Card
                            title={this.props.intl.formatMessage({
                                id: 'detail.condition.title',
                                defaultMessage: '服务活动条件清单属性列表'
                            })}>
                            <Table className="white-space-nowrap"
                                rowKey="id"
                                columns={conditionColumns}
                                pagination={true}
                                dataSource={this.state.detail.conditions}
                                {...TABLE} />
                        </Card>
                        : null
                    }
                    {this.state.detail.dealerQuotas && this.state.detail.dealerQuotas.length > 0
                        ? <Card
                            title={this.props.intl.formatMessage({
                                id: 'detail.dealerInfo.title',
                                defaultMessage: '经销商配额清单属性列表'
                            })}>
                            <Table className="white-space-nowrap"
                                rowKey="id"
                                pagination={true}
                                dataSource={this.state.detail.dealerQuotas}
                                {...TABLE} >
                                <Column title={this.props.intl.formatMessage({
                                    id: 'detail.dealerInfo.column.dealerCode',
                                    defaultMessage: '经销商编号'
                                })} dataIndex="dealerCode" />
                                <Column title={this.props.intl.formatMessage({
                                    id: 'detail.dealerInfo.column.dealerName',
                                    defaultMessage: '经销商名称'
                                })} dataIndex="dealerName" />
                                <Column title={this.props.intl.formatMessage({
                                    id: 'detail.dealerInfo.column.quota',
                                    defaultMessage: '配额台数'
                                })} dataIndex="quota" />
                            </Table>
                        </Card>
                        : null
                    }

                    {
                        this.state.showMulValuePanel &&
                     <Modal title={this.props.intl.formatMessage({
                         id: 'detail.showMulValuePanel',
                         defaultMessage: '多值清单'
                     })}
                     width="30%"
                     footer={null}
                     visible={this.state.showMulValuePanel}
                     onCancel={this.onCloseMulValuePanel}>
                         <Table className="white-space-nowrap"
                             rowKey="id"
                             pagination={true}
                             dataSource={this.state.currentConditionValues}
                             {...TABLE} >
                             <Column title={this.state.currentConditionName === conditionName.产品编号 ? this.props.intl.formatMessage({
                                 id: 'detail.vehicleInfo.column.productCode',
                                 defaultMessage: '产品编号'
                             }) : this.props.intl.formatMessage({
                                 id: 'detail.vehicleInfo.column.productCategoryCode',
                                 defaultMessage: '产品分类编号'
                             })} dataIndex="valueCode" ></Column>
                         </Table>
                     </Modal>
                    
                    }
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.state.loading} onClick={this.props.onCancel}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </Form>
        );
    }
}
DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSuccessReturn: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const mapStateToProps = state => ({
    permissions: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onSuccessReturn: () => {
        dispatch(tableSearch());
        ownProps.history.push(routes.query.url());
    },
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(DetailPanel));
